import { Injectable } from '@angular/core';

import { EMAService } from 'service/EMAService';
import { QuoteBasic } from 'service/QuoteBasic';
import { IMACDService } from 'interface/IMACDService';

@Injectable()
export class MACDService implements IMACDService {

  connection;

  constructor(private emaService:EMAService) {

  }

  compute(quote:QuoteBasic, lday:number, sday:number, mday:number):Array<any> {
    const lemaList = this.emaService.compute(quote, lday);
    const semaList = this.emaService.compute(quote, sday);
    const difList = [];
    const deaList = [];
    const macdList = [];
    const count = quote.close.length;
    const x = 2 / (mday + 1);

    if(lday > 0 && sday > 0 && mday > 0 ) {
      for(let i=0; i<count; i++) {
        const dif = semaList[i] -lemaList[i];
        difList.push(parseFloat(dif.toFixed(4)));
        if (i == 0) {
          deaList.push(0);
          macdList.push(0);
          continue;
        }

        const dea = deaList[i-1] * (1-x) + x*dif;
        deaList.push(parseFloat(dea.toFixed(4)));
        const macd = dif - dea;
        macdList.push(parseFloat(macd.toFixed(4)));
      }
    }

    return [
      difList,
      deaList,
      macdList
    ];
  }

  update(quote:QuoteBasic, lday:number, sday:number, mday:number, difList:Array<any>, deaList:Array<any>, macdList:Array<any>):Array<any> {
    const originCount = quote.close.length;
    const oldCount = difList.length;
    if(lday > 0 && sday > 0 && mday > 0 && originCount > 0) {

      if(oldCount === 0) {
        return this.compute(quote,lday,sday,mday);
      }

      const x = 2 / (mday + 1);

      const lemaList = this.emaService.compute(quote, lday);
      const semaList = this.emaService.compute(quote, sday);

      const dif = parseFloat((semaList[originCount-1] -lemaList[originCount - 1]).toFixed(4));
      const dea = parseFloat((deaList[oldCount-1] * (1-x) + x*dif).toFixed(4));
      const macd = dif - dea;

      if (oldCount < originCount) {
        difList.push(dif);
        deaList.push(dea);
        macdList.push(macd);
      } else {
        difList[originCount-1] = dif;
        deaList[originCount-1] = dea;
        macdList[originCount-1] = macd;
      }
    }

    return [
      difList,
      deaList,
      macdList
    ];
  }
}
